#!/bin/bash
echo "xcheckimage.sh"
dir_now=`pwd`
Nstar_ini_criMin=10 
ObjEllipForAstro_c=0.26
listimage=$1
dir_now=`pwd`
echo $dir_now
#rm -rf listaaaa
mkdir reduc1
cp ~/software/softgft/* reduc1

xcheckEllip (  )
{
    cat image.sex | sort -n -k 3 | head -20 | tail -10 | awk '{print($5)}' >checkimagequality.lst
    head -1 image.sex
   # cat checkimagequality.lst
   # echo "------------"
    sumEllValue=0.0
    N_ellipValue=`wc -l checkimagequality.lst | awk '{print($1)}'`
    for ellipValue in `cat checkimagequality.lst | awk '{print($1)}'`
    do
       echo $ellipValue
        sumEllValue_temp=`echo $ellipValue  $sumEllValue | awk '{print($1+$2)}'`
        sumEllValue=`echo $sumEllValue_temp`
    done
    AverageEllipValue=`echo $sumEllValue $N_ellipValue | awk '{print($1/$2)}'`
#    echo "`date` $fitfile AverageEllipValue=$AverageEllipValue" >>$Monitorfile

    echo "sumEllValue=$sumEllValue  N_ellipValue=$N_ellipValue  AverageEllipValue=$AverageEllipValue"
    if [ ` echo " $AverageEllipValue > $ObjEllipForAstro_c " | bc ` -eq 1  ]
    then
 #      xdisplayOTandnewImg
       echo "This image is not good, pls try next image." 
        SendMessage=`echo "Error_Image_Quality:gft_"$fitfile"_is_not_good"`
#        xSendmsg2Wechat12 $SendMessage
	cd $dir_now
	rm -rf listaaaa
    else
        echo "This image is good enough"
    fi
    cd $dir_now

}

xcheckNumobj ( )
{
 
 sex $fitfile  -c  daofind.sex -DETECT_THRESH 6 -ANALYSIS_THRESH 6 -CATALOG_NAME image.sex 
 Nstar_ini=`cat image.sex | awk '{if(($10/$12)>2)print($0)}' | wc -l | awk '{print($1)}'`
 echo $Nstar_ini
 if [ ` echo " $Nstar_ini > $Nstar_ini_criMin " | bc ` -eq 1 ]
then
	  echo "This $fitfile is good"
	  ls $fitfile >>listgood	
	 echo "current dir is `pwd`"
	 cat listgood
fi
echo "to move the listgood file at `pwd`"
if test -s listgood
then
	mv listgood listaaaa
	mv listaaaa $dir_now
else
	cd $dir_now
	rm -rf listaaaa
fi
#rm -rf reduc1
#if test -s listaaaa
#then
#	echo "have good image"
#	cat listaaaa
#	xbmatch_2.sh listaaaa
#fi
}


rm -rf listgood
for fitfile in `cat $listimage`
do
 	cd $dir_now
 	cp $fitfile reduc1
 	cd reduc1
 	rm -rf image.sex
	xcheckNumobj
	cd reduc1
	xcheckEllip
done
cd $dir_now
rm -rf reduc1
if test -s listaaaa
then
	echo "=========1111======have listaaaa"
else
	echo "no listaaaa"
fi
